﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZHDJ.Core;

namespace ZHDJ.Data.BLL
{
    /// <summary>
    /// 角色-权限帮助类
    /// </summary>
    public class RoleHelper
    {
        /// <summary>
        /// 把一个用户增加到指定角色
        /// </summary>
        /// <param name="loginID"></param>
        /// <param name="roleID"></param>
        public static void AddRole(string loginID, string roleID)
        {
            using (var DB = new DBInstance().DB)
            {
                var role = DB.Roles.Find(roleID);
                var member = DB.PartyOrgMembers.Find(loginID);
                if (role == null || member == null) return;
                role.Users.Add(member);
                DB.SaveChanges();
            }
        }
        /// <summary>
        /// 把一个或多个用户增加到指定角色
        /// </summary>
        /// <param name="loginIDs"></param>
        /// <param name="roleID"></param>
        public static void AddRole(List<string> loginIDs, string roleID)
        {
            using (var DB = new DBInstance().DB)
            {
                var role = DB.Roles.Find(roleID);
                if (role == null)
                {
                    return;
                }
                foreach (var member in loginIDs.Select(item => DB.PartyOrgMembers.Find(item)).Where(member => member != null))
                {
                    role.Users.Add(member);
                    
                }
                DB.SaveChanges();
            }
        }
        /// <summary>
        /// 删除用户的角色
        /// </summary>
        /// <param name="loginID"></param>
        /// <param name="roleID"></param>
        public static void DeleteRole(string loginID, string roleID)
        {
            using (var DB = new DBInstance().DB)
            {
                var role = DB.Roles.Find(roleID);
                var member = DB.PartyOrgMembers.Find(loginID);
                if (role == null || member == null) return;
                role.Users.Remove(member);
                DB.SaveChanges();
            }
        }

        public static void DeleteRole(List<string> loginIDs, string roleID)
        {
            using (var DB = new DBInstance().DB)
            {
                var role = DB.Roles.Find(roleID);
                if (role == null)
                {
                    return;
                }
                foreach (var member in loginIDs.Select(item => DB.PartyOrgMembers.Find(item)).Where(member => member != null))
                {
                    role.Users.Remove(member);

                }
                DB.SaveChanges();
            }
        }
    }
}
